package com.ayou.healthmanagement.service.impl;

import com.ayou.healthmanagement.pojo.HealthMenu;
import com.ayou.healthmanagement.pojo.HealthUser;
import com.ayou.healthmanagement.service.HealthMenuService;
import com.ayou.healthmanagement.mapper.HealthUserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ayou.healthmanagement.mapper.HealthMenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 *
 */
@Service
public class HealthMenuServiceImpl extends ServiceImpl<HealthMenuMapper, HealthMenu>
    implements HealthMenuService {

    @Autowired
    private HealthUserMapper healthUserMapper;

    @Autowired
    private HealthMenuMapper healthMenuMapper;

    @Override
    public List<HealthMenu> getMenus(Integer userId) {
        List<HealthMenu> list = new ArrayList<>();
        HealthUser healthUser = healthUserMapper.selectById(userId);
        //获取顶层菜单
        List<HealthMenu> healthMenus = null;
        if (healthUser.getUserRole().equals("U")){
            healthMenus = healthMenuMapper.selectList(new QueryWrapper<HealthMenu>()
                    .eq("role_key", "user")
                    .eq("parent_id", 0)
                    .orderByAsc("sort_num"));
        }else {
            healthMenus=healthMenuMapper.selectList(new QueryWrapper<HealthMenu>()
                    .eq("parent_id", 0)
                    .orderByAsc("sort_num")
                    .eq("role_key", "admin"));
        }
//        构建树形结构
        for (HealthMenu healthMenu : healthMenus) {
            list.add(buildTree(healthMenu));
        }
        return list;
    }

    public HealthMenu buildTree(HealthMenu healthMenu){
        //查找子菜单
        List<HealthMenu> healthMenus = healthMenuMapper.selectList(new QueryWrapper<HealthMenu>()
                .eq("parent_id", healthMenu.getId())
                .orderByAsc("sort_num"));
//        System.out.println(healthMenus.toString());
        if (!healthMenus.isEmpty()){
            healthMenu.setChildren(healthMenus);
            for (HealthMenu menu : healthMenus) {
                buildTree(menu);
            }
        }
        return healthMenu;
    }
}




